package com.safeneeds.wxmana.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.safeneeds.util.base.BaseAction;
import com.safeneeds.wxmana.util.WxUtil;


@Controller
@RequestMapping("wxAhr")
public class WxAhrAction extends BaseAction{
	public static final String token ="wxczf";
	
	@ResponseBody
	@RequestMapping(value="wxAuthorization.idop",method = RequestMethod.GET)
	public void wxAuthorization(ModelMap model,HttpServletRequest request, HttpServletResponse response) throws IOException{
		// 开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上，GET请求携带参数
		
		String signature =request.getParameter("signature"); 
		String timestamp =request.getParameter("timestamp");
		String nonce =request.getParameter("nonce");
		String echostr =request.getParameter("echostr");
		PrintWriter out = response.getWriter();
		// 将token、timestamp、nonce三个参数进行字典序排序 
		String[] params=new String[]{token,timestamp,nonce };
		Arrays.sort(params);
		// 将三个参数字符串拼接成一个字符串进行sha1加密  
		String clearText=params[0]+params[1]+params[2];
		String algorithm="SHA-1";
		String sign;
		try {
			sign = new String(  
			        Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes())));
			// 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信  
			if(signature.equals(sign)){
				response.getWriter().print(echostr);
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			out.close();
			out=null;
		}  
	}
	

	
	/**
	 * 引导用户打开授权页面
	 */
	@ResponseBody
	@RequestMapping("wxgetCode.idop")
	public void getWxCode(HttpServletResponse response,HttpServletRequest request){
		
	}
	
	/**
	 * 微信接口调试
	 */
	@ResponseBody
	@RequestMapping("wxInter.idop")
	public String wxInter(HttpServletResponse response,HttpServletRequest request){
		
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		
		if(WxUtil.checkSignature(token, signature, timestamp, nonce)){
			return echostr;
		}else{
			return "";
		}
		
	}

}
